#include "Flashbox4LogoContainer.h"
#include "ConstDefined.hrh"
#include "FbUtils.h"
#include "Flashbox4AppUi.h"
#include "Flashbox4.hrh"
#include <fbs.h>
#include "Flashbox4_0x20021B21.rsg"
#include "XmlNode.h"

#ifdef _WAP_CHARGE_
#include "wapcharge.h"
#endif

#include <BAUTILS.H>
#include <UTF.h>
#include <stringloader.h>
#include <aknquerydialog.h>

#define _DEBUG_INFO
#ifdef _DEBUG_INFO
#include <e32svr.h>
#endif

//13821498273

//_LIT(KLogoMainImgFile,"c:\\flashbox4\\data\\logopage.jpg");

CFlashbox4LogoContainer::CFlashbox4LogoContainer () :
	CActive (EPriorityStandard )
{
	
}

CFlashbox4LogoContainer::~CFlashbox4LogoContainer ()
{
	m_Timer.Close();
	Cancel();
	
	delete pLogoMainbmp;
	pLogoMainbmp = NULL;

	delete m_pProgressBar;
	m_pProgressBar = NULL;
#ifdef ADD_TIMER	
	if(iPeriodic)
	{
		iPeriodic->Cancel();
		delete iPeriodic;	
	}
	
#endif
	
#ifdef _CHARGE_ON_LOGO_		
	delete m_pETCharge;
	m_pETCharge = NULL;
	delete m_pSmsContentString;
#endif
	
#if USE_ERRORMSG_DLG
	delete m_pErrorMsgDlg;
	m_pErrorMsgDlg = NULL;
#endif
}

void CFlashbox4LogoContainer::ConstructL (const TRect& aRect )
{
	CreateWindowL ();
	//初始化Logo所需数据
	InitializeControl ();

	SetRect (aRect );
	//全屏显示
	//SetExtentToWholeScreen();	
#ifdef ADD_TIMER
	//开启异步回调函数
	iPeriodic->Start (1000, KFb_Interval, TCallBack (
			CFlashbox4LogoContainer::DrawCallback, this ) );
#endif
	User::LeaveIfError (m_Timer.CreateLocal () );
	CActiveScheduler::Add (this );
	ActivateL ();
}

void CFlashbox4LogoContainer::Draw (const TRect& /*aRect*/) const
{
	CWindowGc& gc = SystemGc ();
	
	//	TInt KBorderSize = 5;
	TRect drawRect (Rect () );
	
	if (pLogoMainbmp )
		gc.DrawBitmap (drawRect, pLogoMainbmp );
	
	//gc.Clear();
	//gc.DrawRect (drawRect);

}

CCoeControl* CFlashbox4LogoContainer::ComponentControl (TInt aIndex ) const
{
	
	switch (aIndex )
	{
	case 0:
		return m_pProgressBar;
	default:
		return NULL;
	}
	//return NULL;
}

TInt CFlashbox4LogoContainer::CountComponentControls () const
{
	return 1;
}

void CFlashbox4LogoContainer::SizeChanged ()
{
	
}

void CFlashbox4LogoContainer::HandleControlEventL (CCoeControl* /*aControl*/, enum TCoeEvent /*aEventType */)
{
	
}

void CFlashbox4LogoContainer::InitializeControl ()
{
	m_pProgressBar = CFbProgressBar::NewL (*this, KFbProgressBarDefaultRect );
	m_pProgressBar->SetProgressBarStyle(EStyleRepeated);
	m_pProgressBar->SetTotalDataLength (MAX_LOGORUNTIMER );
	m_pProgressBar->SetShowTipTextL (R_PROGRESS_LOGO_INFO, KRgbWhite);
	//初始化图片数据
#ifdef __WINSCW__
	pLogoMainbmp = CJpg2Bitmap::BitmapFromJpgFile (KFlashboxLogoImgFile );
#else
	TFileName tmpPath(KFlashboxLogoImgFile);
	AddDrive(tmpPath);
	pLogoMainbmp = CJpg2Bitmap::BitmapFromJpgFile (tmpPath );
#endif

#ifdef ADD_TIMER
	iPeriodic = CPeriodic::NewL (CActive::EPriorityIdle );
	i_Timer = 0;
#endif
	/*
	 #ifdef USE_ERRORMSG_DLG
	 TRect rect(20,120,240-20,200);
	 m_pErrorMsgDlg = CFbShowErrorMsg::NewL(rect);
	 #endif*/
}

#ifdef ADD_TIMER

TInt CFlashbox4LogoContainer::DrawCallback (TAny* pInstance )
{
	CFlashbox4LogoContainer* pNewIns = (CFlashbox4LogoContainer*) pInstance;
	pNewIns->DrawNow ();
	//pNewIns->m_pProgressBar->DrawNow ();
	pNewIns->i_Timer++;
	pNewIns->m_pProgressBar->UpdateRunningStep(6);
	static TBool initHttp = EFalse;
	if (!initHttp && pNewIns->i_Timer >= 4 )
	{
		//GetAppUi()->InitializeHttpEngineL();
		pNewIns->m_State = EStateOnInitHttp;
		pNewIns->m_Timer.After (pNewIns->iStatus, 10000);
		pNewIns->SetActive ();
		initHttp = ETrue;
	}

	if (pNewIns->i_Timer > 2*60*10/*MAX_LOGORUNTIMER*/ )
	{
#ifdef __WINSCW__
		pNewIns->ExitLogo();
#else
		pNewIns->DrawErrorAndTerminateApp();
		pNewIns->i_Timer = 0;
#endif
	}
	
	return 0;
}

void CFlashbox4LogoContainer::ExitLogo ()
{
	i_Timer = 0;
	iPeriodic->Cancel ();
#ifdef __USE_PRO_VIEW__
	GetAppUi()->ActiveViewL(EProMainViewId);
#else
	GetAppUi ()->ActiveViewL (EMainViewId );
#endif

}

#endif


#if USE_ERRORMSG_DLG
void CFlashbox4LogoContainer::DrawErrorAndTerminateApp ()
{
	CAknQueryDialog* exitdlg = CAknQueryDialog::NewL();
	HBufC* msg = StringLoader::LoadL(R_CHARGE_FAIL_PROMPT_TEXT );
	if (exitdlg->ExecuteLD (R_CONFIRM_PROMPT, *msg ) )
	{
		m_State = EStateOnQueryXml;
		m_Timer.After(iStatus, 100000);
		SetActive();
		delete msg;
	}
	else
	{
		//iPeriodic->Cancel ();
		delete msg;
		m_State = EStateOnExit;
		m_Timer.After(iStatus, 50000);
		SetActive();
	}
}
#endif

void CFlashbox4LogoContainer::RunL ()
{
	if (iStatus == KErrNone )
	{
		switch (m_State )
		{
		case EStateOnInitHttp:
			GetAppUi()->InitializeHttpEngineL (this);
			break;
		case EStateChargeInit:
		{
#ifdef _SMS_CHARGE_
			m_State = EStateOnQueryXml;
			TBuf8<256> serverURL;
			serverURL.Copy(KChargServerUrl);
			serverURL.Append(GetAppUi()->m_mobileInfo.iSerialNumber);
			GetAppUi()->IssueHttpGetL(this, serverURL);
#else
#ifdef _WAP_CHARGE_
			CWapCharge *pWapCharge = CWapCharge::NewL();
			pWapCharge->ChargeL(KWapChargeUri);
#endif
#endif		
			break;
		}
		case EStateOnExit:
			GetAppUi()->Exit();
			//ExitLogo();
			break;
		}
	}
}

void CFlashbox4LogoContainer::DoCancel()
{
	m_Timer.Cancel();
}



////////////////////MWebClientObserver接口函数//////////////
/**
 * WebClientEvent()
 * Called when event occurs in CWebClientEngine.
 * @param aEventDescription: A event in textual format, e.g.
 *                           "Transaction Successful"
 */
void CFlashbox4LogoContainer::WebClientEvent (const TInt aEvent, TInt /*aSessionId*/, TInt /*aCode */)
{
	switch (aEvent )
	{
	case KHttpInited:
#ifdef _FEE_CHARGE_
		m_State = EStateChargeInit;
		m_Timer.After(iStatus, 1000*1000);
		SetActive();
#else
		this->ExitLogo();	
#endif
		break;
	case KHttpConnecting:
		break;
	case KHttpTransactionSucceed://连接完成
		break;
	//case KHttpServerError://失败败
	case KHttpTransactionFailed://����������ϴ���
	//	this->ExitLogo();
		//GetAppUi()->Exit();
		break;
	case KHttpTransactionError:
	//case KHttpMHFRunError:
	//case KHttpTransactionCancel://����ȡ��
		DrawErrorAndTerminateApp();
		break;
	case KHttpHeaderContentLength://��ݷ�!����֪ͨ�¼�
		break;
	case KHttpBodyPartReceived:
		break;
	case KHttpBodyReceived:
		break;
	default:
		
		break;
	}
}

/**
 * WebClientHeaderReceived()
 * Called when HTTP header is received.
 * @param aHeaderData: Header field name and value
 */
void CFlashbox4LogoContainer::WebClientHeaderReceived (const TDesC8& aHeaderFiled, const TDesC8& aHeaderVal, TInt /*aSessionId*/ )
{
#ifdef _DEBUG
	RDebug::Printf("< %s : %s", (const char*)aHeaderFiled.Ptr(), (const char*)aHeaderVal.Ptr());
#endif
}

void CFlashbox4LogoContainer::ClientBodyReceived (const TDesC8& aBodyData, TBool aIsLast )
{
	
}


/**
 * WebClientBodyReceivedComplete()
 * Called when a part of the HTTP body is received.
 * @param aBodyData:  Part of the body data received. (e.g. part of
 *                    the received HTML page)
 */
void CFlashbox4LogoContainer::WebClientBodyReceivedComplete (const TDesC8& aBodyData, TInt /*aSessionId*/ )
{
#ifdef _DEBUG
	RDebug::Printf("<body = %s ", (const char*)aBodyData.Ptr());
#endif
	
#ifdef _SMS_CHARGE_
	if (aBodyData.Length () > 0 )
	{
		if (aBodyData.Find (_L8("feeinfo")) == KErrNotFound )
		{
			this->DrawErrorAndTerminateApp ();
		}
		else
		{
			TInt start = aBodyData.Find (_L8("<sms>"));
			TInt end = aBodyData.Find (_L8("</sms>"));
			if(end > start)
			{
				//提示收费
				CAknQueryDialog* exitdlg = CAknQueryDialog::NewL ();
				HBufC* msg = StringLoader::LoadL(R_CHARGE_PROMPT_TEXT );
				if (exitdlg->ExecuteLD (R_CONFIRM_PROMPT, *msg ) )
				{	
					delete msg;
					GetAppUi()->StartSmsCharge(aBodyData);
					this->ExitLogo();
				}
				else
				{
					delete msg;
					GetAppUi()->CancelHttpQueryL();
					m_State = EStateOnExit;
					m_Timer.After(iStatus, 50000);
					SetActive();
				}
			}	
			else
			{
				//不需计费
				this->ExitLogo();
			}
		}
	}
	else
	{
		DrawErrorAndTerminateApp ();
	}
#endif
}

#ifdef _CHARGE_ON_LOGO_
void CFlashbox4LogoContainer::IsCharged (TBool aCharged, TInt aSum, TInt aCurrentNum )
{
	if(m_State == EStateOnGePhoneNumber)
	{
			ExitLogo ();
			return;
	}
	
	if (aCharged )
	{	
			//计费成功
		if (aSum == aCurrentNum )//计费完成
		{
			//向中和服务器发短信
				m_State = EStateOnGePhoneNumber;
				CXmlNode *pSmsCon = CXmlNode::NewLC(_L8("sms"));
				pSmsCon->AddNodeL(_L8("num"), KFbSmsServiceNumber);
				if(m_pSmsContentString)
					pSmsCon->AddNodeL(_L8("con"), m_pSmsContentString->Des());
				else
					pSmsCon->AddNodeL(_L8("con"), _L8("flashbox ..."));
				pSmsCon->AddNodeL(_L8("times"), _L8("1"));
				HBufC8* str = pSmsCon->GetXMLStringL();
				CleanupStack::PushL(str);
				HBufC *pCmd = CnvUtfConverter::ConvertToUnicodeFromUtf8L (str->Des() );
				CleanupStack::PushL(pCmd);
				m_pETCharge->Charge(pCmd->Des());
				CleanupStack::PopAndDestroy(3);
		}
	}
	else
	{
		DrawErrorAndTerminateApp ();	
	}
}

#endif

